<template>
    <Page class="basic company">
        <template #header>
            <EdSelect v-model="params.villageId" :selectParams="proParams"></EdSelect>
            <EdSelect v-model="params.orderStatus" :selectParams="statusParams" @input="handleStatusInput"></EdSelect>
            <EdSelect :class="'tags-select-input'" v-model="params.orderType" :selectParams="orderTypeParams"></EdSelect>
            <!-- <EdCascader v-model="params.categoryId" :cascaderParams="cascaderParams"></EdCascader> -->

            <EdDateTimeRange ref="timeRange" @emit-echo-time-range="emitEchoTimeDate($event, 'pickerTime')"></EdDateTimeRange>
            <el-input v-model="params.address" placeholder="请输入地址" />
            <el-input v-model="params.proposer" placeholder="报单人姓名" />
            <el-input v-model="params.repairer" placeholder="接单人姓名" />

            <el-button class="ed-button ed_black-bottom" @click="search()"><svg-icon class="svg-middle" icon-class="search-svg"/>查询</el-button>
            <el-button class="ed-button ed_white_bottom"  @click="reset()"><svg-icon icon-class="reset-svg"/>重置</el-button>
        </template>
        <PageCard title="工单管理">
            <template #actions>
                <el-popover placement="bottom"
                    width="230"
                    trigger="manual"
                    v-model="visible"
                    style="margin-right: 10px;">
                        <div class="radio_group" v-for="item in levelParams" :key="item.id">
                            <el-radio v-model="increaseRadio" :label="item.value" :class="['m_radio', increaseRadio==item.value ? 'm_radio_top' : '' ]">
                                <svg-icon :icon-class="'urgent' + item.value + '-svg'"/><span :class="['radio_urgent', 'radio_urgent_' + item.value ]">{{item.label}}</span>
                            </el-radio>
                        </div>
                        <div style="text-align: right; margin-top: 10px">
                            <el-button class="ed-button ed_white_bottom" @click="handleIncreaseCancel">取消</el-button>
                            <el-button class="ed-button ed_black-bottom" @click="handleIncreaseSubmit">确定</el-button>
                        </div>
                        <!-- <el-button  :disabled="multipleSelectionIds.length==0" slot="reference" class="ed-button ed_white_bottom" @click="increase()"><svg-icon icon-class="increase-svg"/>提高优先级</el-button> -->
                        <el-button  :disabled="multipleSelectionIds.length==0" slot="reference" class="ed-button ed_white_bottom ed-button36" @click="increase()" v-has="'property:workorder:level'"><i class="el-icon-top"></i>提高优先级</el-button>
                </el-popover>
                <el-button :disabled="multipleSelectionIds.length==0" class="ed-button ed_white_bottom ed-button36" @click="change()" v-has="'property:workorder:transfer'"><i class="el-icon-refresh"></i>指派接单人</el-button>
                <el-button :disabled="multipleSelectionIds.length==0" class="ed-button ed_red_bottom ed-button36" @click="close()" v-has="'property:workorder:close'"><i class="el-icon-close"></i>关闭</el-button>
                <el-button class="ed-button ed_black-bottom ed-button36" @click="add()" v-has="'property:workorder:add'"><svg-icon icon-class="add-svg"/>新增</el-button>
            </template>
            <ApiTable :api="tableApi" ref="table" :params="params"  @selectionData="selectionData">
                <el-table-column type="selection" :selectable="selectable" width="55" ></el-table-column>
                <el-table-column width="90" :show-overflow-tooltip="true" prop="status" label="状态">
                    <template slot-scope="scope">
                        <el-button class="ed-table-bottom ed_1_border" v-if="scope.row.status == 'confirm'">待确认</el-button>
                        <el-button class="ed-table-bottom ed_2_border" v-if="scope.row.status == 'confirmed'">已确认</el-button>
                        <el-button class="ed-table-bottom ed_3_border" v-if="scope.row.status == 'reject'">已驳回</el-button>
                        <el-button class="ed-table-bottom ed_4_border" v-if="scope.row.status == 'pending'">待处理</el-button>
                        <el-button class="ed-table-bottom ed_5_border" v-if="scope.row.status == 'processing'">处理中</el-button>
                        <el-button class="ed-table-bottom ed_7_border" v-if="scope.row.status == 'success'">已完成</el-button>
                        <el-button class="ed-table-bottom ed_8_border" v-if="scope.row.status == 'paid'">已付款</el-button>
                        <el-button class="ed-table-bottom ed_6_border" v-if="scope.row.status == 'cancel'">已撤销</el-button>
                        <el-button class="ed-table-bottom ed_9_border" v-if="scope.row.status == 'close'">已关闭</el-button>
                    </template>
                </el-table-column>
                <el-table-column width="220" :show-overflow-tooltip="true" prop="orderNo" label="工单号">
                    <template slot-scope="scope">
                        <div class="orderno_text"  @click="detail(scope.row)">{{scope.row.orderNo}}</div>
                    </template>
                </el-table-column>
                <el-table-column width="80" :show-overflow-tooltip="true" prop="level" label="优先级">
                    <template slot-scope="scope">
                        <div v-if="scope.row.level==0">
                            <!-- <svg-icon icon-class="urgent0-svg"/> -->
                            <img :src="require('src/icons/svg/urgent0-svg.svg')"/>
                            <span class="radio_urgent radio_urgent_0" style="vertical-align:sub">&nbsp;急</span>
                        </div>

                        <div v-if="scope.row.level==1"><img :src="require('src/icons/svg/urgent1-svg.svg')"/><span class="radio_urgent radio_urgent_1" style="vertical-align:sub">&nbsp;加急</span></div>
                        <div v-if="scope.row.level==2"><img :src="require('src/icons/svg/urgent2-svg.svg')"/><span class="radio_urgent radio_urgent_2" style="vertical-align:sub">&nbsp;紧急</span></div>

                        <!-- <svg-icon :icon-class="'urgent' + scope.row.level + '-svg'"/><span :class="['radio_urgent', 'radio_urgent_' + scope.row.level ]">&nbsp;{{scope.row.level}}</span> -->
                    </template>
                </el-table-column>
                <el-table-column width="250" :show-overflow-tooltip="true" prop="address" label="工单地址">
                    <template slot-scope="scope">
                        <span>{{scope.row.villageName}}{{scope.row.address}}</span>
                    </template>
                </el-table-column>
                <el-table-column width="100" :show-overflow-tooltip="true" prop="orderType" label="工单类型">
                     <template slot-scope="scope">
                        <span>{{returnName(scope.row['orderType'], orderTypeParams.options)}}</span>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="serveDesc" label="工单内容"></el-table-column>
                <el-table-column width="230" :show-overflow-tooltip="true" prop="proposer" label="报单信息">
                    <template slot-scope="scope">
                        <!-- <div>报单人：<span>{{scope.row.openId ? scope.row.proposer.substr(0,1)+'业主' : scope.row.proposer}}&nbsp;<span class="vipClass" v-if="scope.row.important"><svg-icon class="vipSvg" icon-class="vip_svg_1"/></span></span></div>
                        <div v-if="!scope.row.openId">报单人电话：<span>{{scope.row.proposerPhone}}</span></div> -->
                        <div>报单人：<span>{{ scope.row.proposer}}&nbsp;<span class="vipClass" v-if="scope.row.important"><svg-icon class="vipSvg" icon-class="vip_svg_1"/></span></span></div>
                        <div v-if="!scope.row.openId">报单人电话：<span>{{scope.row.proposerPhone}}</span></div>
                        <div>报单时间：<span>{{scope.row.createTime}}</span></div>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="repairer" label="接单信息">
                    <template slot-scope="scope">
                        <div>接单人：<span>{{scope.row.repairer}}</span></div>
                        <div>接单人电话：<span>{{scope.row.repairerPhone}}</span></div>
                    </template>
                </el-table-column>
                <!-- <el-table-column :show-overflow-tooltip="true" prop="repairerPhone" label="接单人电话"></el-table-column> -->

                <!-- <el-table-column :show-overflow-tooltip="true" prop="finishTime" label="完成时间"></el-table-column> -->
                <el-table-column :show-overflow-tooltip="true" prop="finishTime" label="工单结束时间"></el-table-column>
            </ApiTable>
        </PageCard>
        <!-- <EdConfirmDelete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue"></EdConfirmDelete> -->
        <AssignDialog :changeParams="changeParams" ref="transferDialog" :item="item" :isShow="changeDialog" :title_text="title_text" @close-dialog="handleTransferDialogClose" @save-dialog="handleTransferDialogSave"></AssignDialog>
        <EdDialog :width="'460px'" :title="'操作确认'"  v-if="closeDialog"  @close-dialog="closeCancel" @save-dialog="closeSave" ref="closeDia">
            <div class="closeTitle">
                <i class="el-icon-warning"></i>
                <span v-if="multipleSelectionIds.length == 1">是否关闭工单{{multipleSelectionIds[0]}}?</span>
                <span v-else>您选择了{{multipleSelectionIds.length}}个工单,是否都关闭?</span>
            </div>
            <div class="close_textarea">
                <el-input type="textarea" v-model="closeText" :rows="5" placeholder="请简单描述关闭工单的原因，200字符以内" maxlength="200" show-word-limit></el-input>
            </div>
        </EdDialog>
    </Page>
</template>

<script>
import EdCascader from 'src/components/EdCascader.vue'
import EdSelect from 'src/components/EdSelect.vue'
import Page from '../../components/Page.vue'
import PageCard from 'src/views/components/PageCard.vue'
import ApiTable from 'src/components/ApiTable.vue'
import EdDateTimeRange from 'src/components/EdDateTimeRange.vue'
import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
import EdDialog from 'src/components/EdDialog.vue';
import AssignDialog from './AssignDialog.vue'
import { defineComponent } from 'vue'
import { getProjectList, orderList, orderLevel, orderClose, orderTransfer, getrRepairerData } from "./api.js";
import { getDictByCode } from "src/api/dictionaries";
import { returnName } from "src/utils/common.js";
export default defineComponent({
    name: 'building',
    components: { Page, PageCard, ApiTable,EdCascader,EdSelect, EdDateTimeRange, EdConfirmDelete, EdDialog, AssignDialog },
    data() {
        return {
            params:{
                villageId:"",
                // villageName:"",
                orderStatus: [],
                orderType: '',
                // pickerTime: [],
                startTime: '',
                endTime: '',
                address: "",
                proposer: "",
                repairer: "",
            },
            pickerParams:{
                valueFormat:"yyyy-MM-dd"
            },
            levelParams: [],
            proParams: {
                placeholder:"请选择所属项目",
                options: [],
                props: {label:"villageName", value:"villageId"}
            },
            orderTypeParams: {
                placeholder:"请选择工单类型",
                options: [],
                // props: {label:"dictName", value:"dictType"}
            },
            statusParams: {
                placeholder:"请选择状态",
                options: [],
                multiple: true,
                collapseTags: true
                // props: {label:"label", value:"value"}
            },
            cascaderParams:{
                placeholder:"请选择l楼栋名称",
                // props:{label:'label',value:'value',emitPath:false,checkStrictly: true},
                options: [
                    {
                    value: '选项1',
                    label: '黄金糕'
                    }, {
                    value: '选项2',
                    label: '双皮奶'
                    },
                ]
            },
            // 优先级
            visible: false,
            increaseRadio: '',
            // 转派    
            changeDialog: false,
            title_text: '指派工单',
            item: {
                title: '指派工单',
                identification: 'changeDialog',
                ref: 'changeDialog',
            },
            changeParams: null, // 指派人列表 参数
            // 多选
            multipleSelectionIds: [],
            selectionTableData:[],
            // 关闭
            closeDialog: false,
            closeText: ''
        }
    },
    // computed: {
    //     selecedId(){
    //         return this.multipleSelectionIds
    //     },
    // },
    activated(){
        // 获取 所属项目
        getProjectList({pageSize: 999999}).then(res=>{
            this.proParams.options = res.data.records;
        })
        // 获取 工单类型(物业人员-所属职能)
        getDictByCode('member_functions_type').then(res=>{
            this.orderTypeParams.options = res.data.items;
        })
        // 获取 状态
        getDictByCode('serve_status_type').then(res=>{
            this.statusParams.options = res.data.items;
        })
        // 优先级
        getDictByCode('serve_order_level').then(res=>{
            this.levelParams = res.data.items;
        })
        this.$nextTick(()=>{
            this.$refs.table.load(1)
        })
    },
    // mounted(){
    //     // this.params['orderStatus'] = ['pending'];
    //     this.$nextTick(()=>{
    //         this.$refs.table.load(1)
    //     })
    // },
    methods: {
        tableApi:orderList,
        search(){
                // console.log('search-->', this.queryForm)
                this.$refs.table.load(1)
            },
        reset(){
            this.params = {
                villageId:"",
                // villageName:"",
                orderStatus: [],
                orderType: '',
                // pickerTime: [],
                startTime: '',
                endTime: '',
                address: "",
                proposer: "",
                repairer: "",
            };
            this.$refs.timeRange.reset();
            // delete this.params.pickerTime;
            this.$nextTick(()=>{
                this.$refs.table.load(1,10)
            })
        },
        handleStatusInput(data){
            this.params.orderStatus = data;
        },
        emitEchoTimeDate(data){
            // $event 子组件$emit传的参数 
            // console.log('date--->', data)
            this.params['startTime'] = data.startTime;
            this.params['endTime'] = data.endTime;
        },
        selectionData(value){
            // 选中订单号 数组
            this.multipleSelectionIds = value&&value.map((v, i)=>{
                return v.orderNo
            })
            // 选中数据 数组
            this.selectionTableData = value;
            // console.log('select-->', this.multipleSelectionIds, this.selectionTableData)
        },
        add(){
            this.$router.push({
                path: '/property/workorder-add'
            })
        },
        detail(row){
            this.$router.push({
                path: '/property/workorder-detail',
                query: { id: row.orderNo }
            })
        },
        // 提高优先级
        increase(){
            // this.$refs.increaseDialog[0].dialogVisible = true;
            // 待处理、处理中
            let arr = [];
            this.selectionTableData.forEach((v, i)=>{
                if( v.status != 'pending' && v.status != 'processing'){
                    arr.push(v);
                }
            })
            if(arr.length>0) return this.$message.error({ message: '所选项状态不对！', center: true })
            this.visible = true;
        },
        handleIncreaseCancel(){
            this.visible = false;
            this.increaseRadio = '';
            this.$refs.table.$children[0].clearSelection();
        },
        handleIncreaseSubmit(){
            if(!this.increaseRadio) return this.$message.warning({ message: "未勾选！", center: true })
            let params = {
                orderId: this.multipleSelectionIds.join(','),
                level: this.increaseRadio
            };
            // console.log('increaseRadio', params)
            // return
            orderLevel(params).then((res)=>{
                if(res.code == 20000) {
                    this.$message.success({
                        message: '操作成功！',
                        duration: 2000,
                        center:true
                    });
                    this.visible = false;
                    this.increaseRadio = '';
                    this.$refs.table.$children[0].clearSelection();
                    this.$refs.table.load()
                }
            })
        },
        // 转派
        change(){
            // 前置条件
            // 1. 待处理、处理中、待确认 confirm
            // 2. 同 小区、工单类型
            let arr = [], arr_1 = [], arr_2 = [];
            this.selectionTableData.forEach((v, i)=>{
                // 判断状态
                if(v.status != 'pending' && v.status != 'processing' && v.status != 'confirm') arr.push(v);
                // 判断类型
                if(v['orderType'] != this.selectionTableData[0]['orderType']) arr_1.push(v);
                // 判断小区
                if(v['villageName'] != this.selectionTableData[0]['villageName']) arr_2.push(v);
            })
            if(arr.length>0) return this.$message.error({ message: '所选项状态不对！', center: true });
            if(arr_1.length>0) return this.$message.error({ message: '所选项工单类型需一致！', center: true });
            if(arr_2.length>0) return this.$message.error({ message: '所选项所属项目需一致！', center: true });
            if(this.selectionTableData.length == 1){
                this.title_text = '工单 ' + this.selectionTableData[0]['orderNo'] + ' 指派给：';
            }else{
                this.title_text = this.selectionTableData.length + '个工单指派给：';
            } 

            this.changeParams = {
                villageId: this.selectionTableData[0]['villageId'],
                userFunction: this.selectionTableData[0]['orderType'],
            }
            this.changeDialog = true;
        },
        handleTransferDialogClose(){
            this.changeDialog = false;
            this.$refs.table.$children[0].clearSelection();
        },
        handleTransferDialogSave(data){
            // console.log('id', data)
            if(!data) {
                this.$refs.transferDialog.cancelStatus()
                this.changeParams = {
                    villageId: this.selectionTableData[0]['villageId'],
                    userFunction: this.selectionTableData[0]['orderType'],
                }
                return this.$message.warning({ message: "未勾选！", center: true })
            }
            let params = {
                orderId: this.multipleSelectionIds.join(','),
                repairerId: data['id'],
                repairer: data['name'],
                repairerPhone: data['mobile'],
            };
            // console.log('paa', params)
            // return
            orderTransfer(params).then((res)=>{
                if(res.code == 20000) {
                    this.$message.success({
                        message: '操作成功！',
                        duration: 2000,
                        center:true
                    });
                    this.changeDialog = false;
                    this.$refs.table.$children[0].clearSelection();
                    this.$refs.table.load()
                }
            }).catch(()=>{
                this.$refs.transferDialog.cancelStatus()
            })
        },
        // 关闭
        close(){
            // 待处理、处理中
            let arr = [];
            this.selectionTableData.forEach((v, i)=>{
                if( v.status != 'pending' && v.status != 'processing'){
                    arr.push(v);
                }
            })
            if(arr.length>0) return this.$message.error({ message: '所选状态不对！', center: true })
            this.closeDialog = true;
        },
        closeSave(){
            if(!this.closeText) {
                this.$refs.closeDia.hideLoading()
                return this.$message.error({ message: '请填写关闭原因！', center: true });
            }
            let params = {
                orderId: this.multipleSelectionIds.join(','),
                status: 'close',
                reason: this.closeText
            };
            // console.log('close', params)
            // return 
            orderClose(params).then((res)=>{
                if(res.code == 20000) {
                    this.$message.success({
                        message: '操作成功！',
                        duration: 2000,
                        center:true
                    });
                    this.closeDialog = false;
                    this.closeText = '';
                    this.$refs.table.$children[0].clearSelection();
                    this.$refs.table.load()
                }
            })
        },
        closeCancel(){
            this.closeDialog = false;
            this.closeText = '';
            this.$refs.table.$children[0].clearSelection();
        },
        returnName(val, options){
            return returnName(val, options)
        },
        formatDate(row, column) {
            // 获取单元格数据
            let date = row[column.property];
            if (date) {
                return this.transformDate(date)
            } else {
                return ''
            }
        },
        //标准时间格式转yyyy-MM-dd HH:mm:ss
        transformDate(date) {
            if (date) {
                let dt = new Date(date);
                return dt.getFullYear() + '-' +
                    ((dt.getMonth() + 1) < 10 ? ('0' + (dt.getMonth() + 1)) : (dt.getMonth() + 1)) + '-' +
                    (dt.getDate() < 10 ? ('0' + dt.getDate()) : dt.getDate()) + ' ' +
                    (dt.getHours() < 10 ? ('0' + dt.getHours()) : dt.getHours()) + ':' +
                    (dt.getMinutes() < 10 ? ('0' + dt.getMinutes()) : dt.getMinutes()) 
                    // (dt.getSeconds() < 10 ? ('0' + dt.getSeconds()) : dt.getSeconds())
            } else {
                return ''
            }
        },
        selectable(row, index){
            return true
        }
    },
})
</script>

<style lang="scss" scoped>
    :deep .el-radio.m_radio{
        display: inline-block;
        width: 100%;
        padding: 6px 6px 6px 20px;
        font-family: 'Noto Sans SC';
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        line-height: 22px;
        .el-radio__input.is-checked + .el-radio__label{
            color: #EED096;
        }
        .el-radio__input.is-checked .el-radio__inner{
            border-color: #EED096;
            background-color: #EED096;
        }
        .el-radio__input .el-radio__inner:hover{
                 border-color: #EED096;
            
        }
        .radio_urgent{
            margin-left: 4px;
        }
    }
    :deep .el-radio.m_radio:hover{
        background-color: #FEF9F0;
    }
    :deep .el-radio.m_radio_top{
        background-color: #FEF9F0;
    }
    // .radio_group{
        // border-bottom: 1px solid #eef2f9; 
        .radio_urgent_0{
            color: #EED096;
        }
        .radio_urgent_1{
            color: #F3B385;
        }
        .radio_urgent_2{
            color: #EE7171;
        }
    // }

    .orderno_text{
        cursor: pointer;
        font-family: 'Noto Sans SC';
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        line-height: 22px;
        color: #6F8EC6;
        text-decoration: underline;
    }
    :deep .closeTitle{
        font-family: 'PingFang SC';
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 18px;
        color: #1E1E1E;
        margin-left: 25px;
        .el-icon-warning{
            color: #E6A23C;
            font-size: 16px;
            margin-right: 3px;
        }
    }
    .close_textarea{
        width: 88%;
        margin-left: 25px;
        margin-top: 20px;
    }
    .vipSvg{
        padding: 2px 4px;
        background: linear-gradient(284.04deg, #EED096 0%, #FFF1D5 100%);
        width: 24px;
        height: 12px;
        // background: #414448;
        border-radius: 5px;
    }
    :deep{
        .tags-select-input{
            height: 40px;
            .el-select__tags{
                height: 40px;
                overflow: hidden;
                white-space: nowrap;
                flex-wrap: nowrap;
            }
            .el-select__tags-text{
                max-width: 85px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                display: inline-block;
            }
        }
    }
</style>